//
//  ViewController.m
//  CollectToDesktop
//
//  Created by zhangbin on 15/3/3.
//  Copyright (c) 2015年 godbe. All rights reserved.
//

#import "ViewController.h"
#import "AppDelegate.h"

@interface ViewController ()

- (IBAction)safariFunction:(id)sender;
- (IBAction)provision:(id)sender;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/**
 *  利用safari功能生成webclip
 *
 *  @param sender
 */
- (IBAction)safariFunction:(id)sender {
    __weak AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    
    //配置返回值
    [appDelegate.httpServer get:@"/old" withBlock:^(RouteRequest *request, RouteResponse *response) {
        [response setStatusCode:302]; // or 301
        [response setHeader:@"Location" value:@"data:text/html;charset=UTF-8,<html><head><meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no'/><meta name='apple-mobile-web-app-capable' content='yes'/></head><body><img src=\"\" alt=\"\"></body><script>if (window.navigator.standalone){window.location.href='sample://';}</script></html>"];
    }];
    
    //跳转
    UInt16 port = appDelegate.httpServer.port;
    NSLog(@"%u", port);
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://localhost:%u/old", port]]];


}

/**
 *  利用profile生成webclip
 *
 *  @param sender
 */
- (IBAction)provision:(id)sender {
    //模板位置
    NSString *templatePath = [[NSBundle mainBundle] pathForResource:@"phone_template" ofType:@"mobileconfig"];
    
    //目标位置
    NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *path = [documentsDirectory stringByAppendingPathComponent:@"profile.mobileconfig"];
    
    if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
        [[NSFileManager defaultManager] removeItemAtPath:path error:nil];
    }
    BOOL success = [[NSFileManager defaultManager] copyItemAtPath:templatePath toPath:path error:nil];

    __weak AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    UInt16 port = appDelegate.httpServer.port;
    NSLog(@"%u", port);
    if (success) [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://localhost:%u/profile.mobileconfig", port]]];
    else NSLog(@"Error generating profile");
}
@end
